//
//  InChannelSoundsViewController.m
//  Inner  Voice
//
//  Created by Martin.Wang on 16/2/29.
//  Copyright © 2016年 徐海宇. All rights reserved.
//

#import "InChannelSoundsViewController.h"

#import "InChannelSoundCollectionViewCell.h"

#import "InChannelSoundCollectionReusableView.h"

#import "InSoundFavouriteTool.h"

#import <AFNetworking.h>

#import <MJRefresh.h>

#import "InSoundTableViewController.h"

#import "RecommenViewController.h"

#import "AppDelegate.h"

#import "InSoundTool.h"

#import "InSound.h"

#define appDelegate ((AppDelegate *)[[UIApplication sharedApplication]delegate])

@interface InChannelSoundsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,channelConcernBtn>

@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@property (nonatomic, strong) NSMutableArray *recommendSounds;

@property (nonatomic, assign) int page;

@property (nonatomic, strong) InChannelSoundCollectionReusableView *reusableView;

@end

static NSString *kcellIdentifier = @"channelsoundCellID";

static NSString *kheaderIdentifier = @"channelsoundReusableView";

@implementation InChannelSoundsViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    
    self.navigationItem.title = @"频道类别";
    
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    
    //通过Nib生成cell，然后注册 Nib的view需要继承 UICollectionViewCell
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"InChannelSoundCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kcellIdentifier];
    
    //注册headerView Nib的view需要继承UICollectionReusableView
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"InChannelSoundCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kheaderIdentifier];

    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    self.page = 1;
    
    [self channelHotSoundsWithPage:self.page];
    
    // 上拉刷新
    self.myCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page++;
        
        [self channelHotSoundsWithPage:self.page];
        
    }];
    }
    // Do any additional setup after loading the view from its nib.
}

- (NSMutableArray*)recommendSounds{
    if (_recommendSounds == nil) {
        _recommendSounds = [NSMutableArray array];
    }
    return _recommendSounds;
}

- (void)channelHotSoundsWithPage:(int)page{
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    NSString *url = [NSString stringWithFormat:@"http://1.wangtest11.applinzi.com/home/Banner/backchannelHotSound?page=%d&channelid=%@",page,self.dic[@"id"]];
    
    AFHTTPSessionManager *httpSession = [AFHTTPSessionManager manager];
    
    [httpSession GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        
        NSArray *sounds = dic[@"data"];
        
        int a = (int)[sounds count];
        
        for (int b = 0; b < a; b++) {
            
            [self.recommendSounds addObject:sounds[b]];
            
        }
        
        [self.myCollectionView reloadData];
        
        [self.myCollectionView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"频道类别 ERROR %@",error);
        
    }];
    }
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    self.reusableView =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:kheaderIdentifier   forIndexPath:indexPath];

    [self.reusableView loadDataWithChannelDic:self.dic];
    
    self.reusableView.delegate = self;
    
    return self.reusableView;
}

#pragma mark -CollectionView datasource
//section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.recommendSounds.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //重用cell
    InChannelSoundCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcellIdentifier forIndexPath:indexPath];

    NSDictionary *sound = self.recommendSounds[indexPath.row];
    
    if (!sound) {
        return cell;
    }
    
    [cell loadImageWithStr:sound[@"pic_200"]];
    
    cell.soundName.text = sound[@"name"];
    
    return cell;
    
}

//选择播放歌曲
- (void)playWithSound:(NSDictionary*)sound{
    
    NSLog(@"频道类别%@",sound);
    
    [appDelegate.InPlayerViewController.inplayer stop];
    
    
    
    InSound *inSound = [[InSound alloc]init];
    
    inSound.inSound_icon = sound[@"pic_100"];
    inSound.inSound_name = sound[@"name"];
    inSound.inSound_Url = sound[@"source"];
    inSound.sound_id = sound[@"id"];
    //    inSound.inSound_id = (NSInteger)sound[@"user_id"];
    
    [InSoundTool insertInToSound:inSound];//本地数据库插入播放过的歌曲
    
    [appDelegate.InPlayerViewController.inplayer playWithUrl:[NSURL URLWithString:sound[@"source"]] showView:appDelegate.InPlayerViewController.sliderView];
    
    //播放页面的歌曲信息里面的模型
    appDelegate.InPlayerViewController.inSound = inSound;
    
    NSMutableArray *playingArray = [InSoundTool soundArray];
    
    appDelegate.InPlayerViewController.playingSoundArray = playingArray;
    
    NSLog(@"频道类别%@",sound[@"source"]);
    
    InSoundTableViewController *controller = [[InSoundTableViewController alloc] init];
    
    __weak typeof (self) temp = self;
    
    controller.dic = sound;
    
    //push用在UINavigationController下得语句
    [temp.navigationController pushViewController:controller animated:YES];
    
    
    
}


//选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    
    NSDictionary *sound = self.recommendSounds[indexPath.row];
    
    if (!sound) {
        return;
    }

    
    [self playWithSound:sound];
    

    
}

//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.frame.size.width/2.2, self.view.frame.size.width/3);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, self.view.frame.size.width/50, 10, self.view.frame.size.width/50);
    
}
//返回头headerView的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    CGSize size={self.view.frame.size.width,270};
    
    return size;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark- 代理方法
- (void)channelConcernBtn {
    [self alertViewShow];
}

//没有登录情况下
#pragma mark -alertView
- (void)alertViewShow {
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *user_id = [userDefaults valueForKey:@"u_id"];
    
    if (user_id == nil) {
        [alertView show];
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        InLoginViewController *loginController = [[InLoginViewController alloc]initWithNibName:@"InLoginViewController" bundle:nil];
        
        [self presentViewController:loginController animated:YES completion:nil];
        
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    if (self.reusableView.attentionBtn.selected == YES) {
        [self channelConcernLabelNumberChange];
    }else {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        NSString *user_id = [userDefault valueForKey:@"u_id"];
        [InSoundFavouriteTool deleteChannel:self.dic[@"id"] WithUser_id:user_id];
    }
    
}

- (void)channelConcernLabelNumberChange {
    if ([AppDelegate shareAppdelegate].canConnectedToTheInternet) {

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    //    [userDefault setValue:@"1111" forKey:@"u_id"];
    
    NSString *user_id = [userDefault valueForKey:@"u_id"];
    
    AFHTTPSessionManager *httpSessionManager = [AFHTTPSessionManager manager];
    
    NSString *url = [NSString stringWithFormat:@"http://1.wangtest11.applinzi.com/home/Banner/userFavouritechannels?userid=%@&channelid=%@&like_count=%@",user_id,self.dic[@"id"],self.reusableView.attentionCountLabel.text];
    
    [httpSessionManager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"  success   ");
        
        [InSoundFavouriteTool insertChannel:self.dic[@"id"] WithUser_id:user_id];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    }else {
        [self showAlertView:@"当前网络不可用"];
    }
}
#pragma mark - 封装UIAlertView方法，直接调用就可以显示提示
-(void)showAlertView:(NSString *)string {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
